package com.ibm.testbed.script.history;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.internal.resources.File;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.views.IViewDescriptor;


/**
 * The Show View dialog.
 */
public class HistorysWizardPage extends WizardPage {

	private CheckboxTableViewer tableViewer_port;
	
	private Object parent;

	private ISelection selection;

	private static final String DIALOG_SETTING_SECTION_NAME = "EditMappingRulesDialog"; //$NON-NLS-1$

	private Button okButton;

	private History history;
	
	public History getHistory() {
		return history;
	}

	public IFile getFile() {
		return history.getFile();
	}

	private IViewDescriptor[] viewDescs = new IViewDescriptor[0];

	public CheckboxTableViewer getTableViewer_port() {
		return tableViewer_port;
	}

	/**
	 * Constructor for SampleNewWizardPage.
	 * 
	 * @param pageName
	 */
	public HistorysWizardPage(ISelection selection) {
		super("wizardPage");
		setTitle("Edit history");
		setDescription("This wizard is a history.");
		this.selection = selection;
	}

	public void setSelection(ISelection selection){
		this.selection = selection;
	}
	
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 1;
		layout.verticalSpacing = 9;

//		dialogChanged();
		createPortsGroup(container);
		
		setControl(container);
		
		if(this.selection instanceof TreeSelection){
			TreeSelection treeSelection = (TreeSelection)this.selection;
			
			if(treeSelection.getFirstElement() instanceof File){
				File file = (File)treeSelection.getFirstElement();
				
				history = HistoryManager.getInstance().getHistory(file);
				List<API> apis = history.getApis();
				List<Param> inputs = new ArrayList<Param>();
				for(API api : apis){
					List<Param> params = api.getParams();
					for(Param param : params){
						param.setApi(api);
						inputs.add(param);
					}
				}
				tableViewer_port.setInput(inputs.toArray());
				for(Param param : inputs){
					if(param.getActive() != null && param.getActive().equals(HistoryManager.getInstance().getResult(param.getResults()).getValue())){
						tableViewer_port.setChecked(param, true);
					}
				}
				
//				file.getResourceAttributes().setHidden(true);
			}
		}
	}
	
	private void createPortsGroup(Composite parent) {
		Group group = new Group(parent, SWT.NONE);

		group.setLayout(new FillLayout());
		GridData gridData = new GridData(GridData.FILL_BOTH);
		gridData.horizontalSpan = 3;
		group.setLayoutData(gridData);
		group.setText("Selecte history");

		Table table = new Table(group, SWT.BORDER | SWT.FULL_SELECTION
				| SWT.CHECK);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableColumn tc = new TableColumn(table, SWT.NONE);
		tc.setWidth(25);
		
		tc = new TableColumn(table, SWT.NONE);
		tc.setWidth(120);
		tc.setText("API");
		
		tc = new TableColumn(table, SWT.NONE);
		tc.setWidth(300);
		tc.setText("Params");
		
		tc = new TableColumn(table, SWT.NONE);
		tc.setWidth(120);
		tc.setText("Return");

		tableViewer_port = new CheckboxTableViewer(table);
		tableViewer_port.setLabelProvider(labelProvider);
		tableViewer_port.setContentProvider(contentProvider);
		tableViewer_port.addCheckStateListener(new ICheckStateListener() {

			@Override
			public void checkStateChanged(CheckStateChangedEvent event) {

			}
		});
	}
	
	private ITableLabelProvider labelProvider = new ITableLabelProvider() {

		@Override
		public void addListener(ILabelProviderListener listener) {
			tableViewer_port.addDoubleClickListener(new   IDoubleClickListener(){ 
				public   void   doubleClick(DoubleClickEvent   event) { 
					IStructuredSelection   selection=(IStructuredSelection)event.getSelection(); 
					Param param = (Param)selection.getFirstElement(); 
					Result result = HistoryManager.getInstance().getResult(param.getResults());
					String value = "";
					if(result.getType().equals(Result.type_return)){
						value = result.getValue();
					}else{
						value = result.getType();
					}
					MessageDialog.openInformation(null, param.getApi().getValue()+HistoryManager.setParameters(param), value); 
				} 
			} 
			); 
		}

		@Override
		public void dispose() {
			// TODO Auto-generated method stub

		}

		@Override
		public boolean isLabelProperty(Object element, String property) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public void removeListener(ILabelProviderListener listener) {
			// TODO Auto-generated method stub

		}

		@Override
		public Image getColumnImage(Object element, int columnIndex) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public String getColumnText(Object element, int columnIndex) {
			// TODO Auto-generated method stub
			Param param = (Param)element;
			if(columnIndex == 0){
				
			}
			if (columnIndex == 1) {
				return param.getApi().getValue();
			}
			if (columnIndex == 2) {
				return HistoryManager.setParameters(param);
			}
			if (columnIndex == 3) {
				Result result = HistoryManager.getInstance().getResult(param.getResults());
				if(result.getType().equals(Result.type_return)){
					return result.getValue();
				}
				return result.getType();
			}
			return null;
		}
	};

	private IStructuredContentProvider contentProvider = new IStructuredContentProvider() {

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			// TODO Auto-generated method stub

		}

		@Override
		public void dispose() {
			// TODO Auto-generated method stub

		}

		@Override
		public Object[] getElements(Object inputElement) {
			// TODO Auto-generated method stub
			if (inputElement != null){
					return (Object[])inputElement;
			}
			return new Object[] {};
		}
	};
	/**
	 * Returns the descriptors for the selected views.
	 * 
	 * @return the descriptors for the selected views
	 */
	public IViewDescriptor[] getSelection() {
		return viewDescs;
	}

	/**
	 * Since OK was pressed, write widget values to the dialog store so that
	 * they will persist into the next invocation of this dialog
	 */
	protected void saveWidgetValues() {
		Object[] inputs = (Object[]) tableViewer_port.getInput();
		for(Object object : inputs){
			Param param = (Param)object;
			if(tableViewer_port.getChecked(param)){
				param.setActive(HistoryManager.getInstance().getResult(param.getResults()).getValue());
			}else{
				param.setActive("");
			}
			param.getRoot().setAttribute("active", param.getActive());
		}
	}

	/**
	 * Notifies that the selection has changed.
	 * 
	 * @param event
	 *            event object describing the change
	 */
	public void selectionChanged(SelectionChangedEvent event) {
		updateSelection(event);
		updateButtons();
	}

	/**
	 * Update the button enablement state.
	 */
	protected void updateButtons() {
		if (okButton != null) {
			okButton.setEnabled(getSelection().length > 0);
		}
	}

	/**
	 * Update the selection object.
	 */
	protected void updateSelection(SelectionChangedEvent event) {
		ArrayList descs = new ArrayList();
		IStructuredSelection sel = (IStructuredSelection) event.getSelection();
		for (Iterator i = sel.iterator(); i.hasNext();) {
			Object o = i.next();
			if (o instanceof IViewDescriptor) {
				descs.add(o);
			}
		}
		viewDescs = new IViewDescriptor[descs.size()];
		descs.toArray(viewDescs);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.window.Dialog#getDialogBoundsSettings()
	 * 
	 * @since 3.4
	 */
	protected IDialogSettings getDialogBoundsSettings() {
		return getDialogSettings();
	}
}
